import { createRouter, createWebHashHistory } from "vue-router";

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "",
      component: () => import("@/view/index.vue"),
      redirect: "/home",
      children: [
        {
          path: "/home",
          name: "home",
          meta: {
            title: "首页",
            requireAuth: true,
          },
          component: () => import("@/view/home/index.vue"),
        },
        {
          path: "/my",
          name: "my",
          component: () => import("@/view/my/index.vue"),
          meta: {
            title: "我的",
            requireAuth: true,
          },
        },
        {
          path: "/add",
          name: "add",
          component: () => import("@/view/post/add.vue"),
          meta: {
            title: "发布",
            requireAuth: true,
          },
        },
      ],
    },

    {
      path: "/login",
      name: "login",
      component: () => import("@/view/auth/login.vue"),
    },
    {
      path: "/register",
      name: "register",
      component: () => import("@/view/auth/register.vue"),
    },
    {
      path: "/preview",
      component: () => import("@/view/post/preview.vue"),
      name: "preview",
      meta: {
        title: "预览",
        requireAuth: true,
      },
    },
    {
      path: "/post/:id",
      component: () => import("@/view/post/detail.vue"),
      name: "detail",
      meta: {
        title: "详情",
        requireAuth: true,
      },
    },

    {
      path: "/my/post",
      component: () => import("@/view/my/post.vue"),
      name: "myPost",
      meta: {
        title: "我的帖子",
        requireAuth: true,
      },
    },
  ],
});

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    if (localStorage.getItem("token")) {
      next();
    } else {
      next({
        path: "/login",
        query: { redirect: to.fullPath },
      });
    }
  } else {
    next();
  }
});

export default router;
